package com.zerone.pay.trade.web.controller;

import com.acooly.core.utils.Ids;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.common.collect.Maps;
import com.zerone.pay.gateway.WXPayConfigMore;
import com.zerone.pay.trade.service.TradeService;
import com.zerone.pay.trade.service.order.AliTradeStatusEnum;
import com.zerone.pay.trade.service.order.TradePayNotifyOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 木鱼 muyu@yiji.com
 */
@Controller
@RequestMapping({"/notify/"})
public class PayNotifyController {

  protected static final Logger logger = LoggerFactory.getLogger(PayNotifyController.class);

  @Autowired
  private TradeService tradeService;

  @Autowired
  private WXPayConfigMore wxPayConfigMore;


  @RequestMapping("alipay")
  @ResponseBody
  public String alipay(HttpServletRequest request, @RequestBody String requestBody) throws AlipayApiException {
    logger.info("收到支付宝付款回执通知:"+requestBody );
    Map<String, String> params = Maps.newHashMap();
    for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
      if (entry.equals("sign_type")) {
        continue;
      }
      params.put(entry.getKey(), entry.getValue()[0]);
    }

    if (!AlipaySignature.rsaCheckV1(params, wxPayConfigMore.getKey(), "utf-8",
        Configs.getSignType())) {
      return "fail:校验签名不通过";
    }
    if(!Configs.getAppid().equals(request.getParameter("app_id"))){
        logger.info("appid不一致，忽略");
        return "fail";
    }

    TradePayNotifyOrder order = new TradePayNotifyOrder();
    order.setGid(Ids.gid());
    order.setOutTradeNo(request.getParameter("out_trade_no"));
    order.setAliTradeStatus(AliTradeStatusEnum.valueOf(request.getParameter("trade_status")));
    order.setBuyerId(request.getParameter("buyer_id"));
    order.setTotalAmount(request.getParameter("total_amount"));
    order.setPartnerId(Ids.getDid());
    tradeService.payNotify(order);
    return "success";
  }


  @RequestMapping("wechatPay")
  @ResponseBody
  public String wechatPay(HttpServletRequest request, @RequestBody String requestBody) {
    logger.info("收到微信付款回执通知:"+requestBody );
    try{
        WXPayUtil.isSignatureValid(requestBody,wxPayConfigMore.getKey());
        logger.info("验签不过");
      Map<String,String> param = WXPayUtil.xmlToMap(requestBody);
      TradePayNotifyOrder order = new TradePayNotifyOrder();
      order.setGid(Ids.gid());
      order.setOutTradeNo(param.get("out_trade_no"));
      if(param.get("result_code").equals("SUCCESS")){
        order.setAliTradeStatus(AliTradeStatusEnum.TRADE_FINISHED);
      }else{
        order.setAliTradeStatus(AliTradeStatusEnum.TRADE_CLOSED);
      }
      order.setBuyerId(param.get("openid"));
      order.setTotalAmount(param.get("total_fee"));
      order.setPartnerId(Ids.getDid());
      tradeService.payNotify(order);
      Map<String,String> result = Maps.newHashMap();
      result.put("return_code","SUCCESS");
      result.put("return_msg","OK");
      return WXPayUtil.mapToXml(result);
    }catch (Exception e){
      Map<String,String> result = Maps.newHashMap();
      result.put("return_code","FAIL");
      result.put("return_msg",e.getMessage());
      try {
        return WXPayUtil.mapToXml(result);
      } catch (Exception e1) {
        e1.printStackTrace();
      }
    }
    return "success";
  }

}
